package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.manage.domain.db.UserInfo;
import com.tanhua.manage.domain.mongo.FollowUser;
import com.tanhua.manage.domain.mongo.Video;
import com.tanhua.manage.domain.vo.PageResult;
import com.tanhua.manage.domain.vo.VideoVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class VideoService {
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Autowired
    private FastFileStorageClient client;
    @Reference
    private VideoApi videoApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 发布小视频
     * @param videoThumbnail
     * @param videoFile
     * @return
     */
    public void post(MultipartFile videoThumbnail, MultipartFile videoFile) {

        try {
            String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
            //视频上传到fastDFS，接收视频地址
            String videoFilename = videoFile.getOriginalFilename();
            String videoExtension = videoFilename.substring(videoFilename.lastIndexOf(".")+1);
            //p1：文件的输入流，p2：文件大小，p3：文件的后缀名（不包含.），p4：null
            StorePath storePath = client.uploadFile(videoFile.getInputStream(),videoFile.getSize(),videoExtension,null);

            String videoUrl = fdfsWebServer.getWebServerUrl()+storePath.getFullPath();

            //构建video对象
            Video video = new Video();
            video.setVideoUrl(videoUrl);
            video.setUserId(UserHolder.getUserId());
            video.setPicUrl(picUrl);
            video.setText("黑马出品");

            //调用api保存视频数据到mongodb
            videoApi.add(video);
        } catch (IOException e) {
            log.error("上传视频封面失败",e);
            throw new TanHuaException("上传视频封面失败");
        }
    }

    /**
     * 小视频列表分页查询
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult<VideoVo> findPage(Long page, Long pageSize) {
        PageResult pageResult = videoApi.findPage(page,pageSize);
        List<Video> videoList = pageResult.getItems();

        List<VideoVo> voList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(videoList)){
            List<Long> userIds = videoList.stream().map(Video::getUserId).collect(Collectors.toList());
            List<UserInfo> userInfoList = userInfoApi.findByBatchId(userIds);
            Map<Long, UserInfo> userInfoMap = userInfoList.stream().collect(Collectors.toMap(UserInfo::getId, u -> u));

            voList = videoList.stream().map(video -> {
                VideoVo vo = new VideoVo();
                BeanUtils.copyProperties(video, vo);

                vo.setCover(video.getPicUrl());
                vo.setSignature(video.getText());
                vo.setId(video.getId().toHexString());

                UserInfo userInfo = userInfoMap.get(video.getUserId());
                BeanUtils.copyProperties(userInfo, vo);

                //设置是否关注
                String key = "follow_user_" + UserHolder.getUserId() + "_" + video.getUserId();
                if (redisTemplate.hasKey(key)) {
                    vo.setHasFocus(1);
                }
                return vo;
            }).collect(Collectors.toList());

        }
        pageResult.setItems(voList);
        return pageResult;
    }

    /**
     * 关注视频作者
     * @param followUserId
     */
    public void focusUser(Long followUserId) {
        Long loginUserId = UserHolder.getUserId();
        FollowUser followUser = new FollowUser();
        followUser.setUserId(loginUserId);
        followUser.setFollowUserId(followUserId);

        videoApi.followUser(followUser);
        String key = "follow_user_"+ loginUserId + "_" + followUserId;
        redisTemplate.opsForValue().set(key,1);
    }

    /**
     * 取消关注视频作者
     * @param followUserId
     */
    public void userUnFocus(Long followUserId) {
        Long loginUserId = UserHolder.getUserId();
        FollowUser followUser = new FollowUser();
        followUser.setFollowUserId(followUserId);
        followUser.setUserId(loginUserId);

        videoApi.unfollowUser(followUser);
        String key = "follow_user_"+ loginUserId + "_" + followUserId;
        redisTemplate.delete(key);
    }
}
